package com.demo.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class CountDownService {

    private static final Logger log = LoggerFactory.getLogger(CountDownService.class);

    @Autowired
    @Qualifier("countDownExecutor")
    private ThreadPoolExecutor executor;

    @PostConstruct
    public void startCountDown() {
        CountDownLatch latch = new CountDownLatch(60); // 60 秒
        executor.execute(() -> {
            while (latch.getCount() > 0) {
                long remaining = latch.getCount();
                log.info("倒计时 {} 秒，当前时间：{}", remaining,
                        LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
                latch.countDown();
            }
            log.info("倒计时结束！");
        });
    }
}